package com.itheima.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.itheima.pojo.R;
import com.itheima.utils.AliOSSUtils;
import jdk.nashorn.internal.objects.annotations.Where;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    //通过全局配置yml文件直接获取存储文件位置
    //@Value("${reggie.path}")
    //private String dir;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accesskey;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretkey;

    //String accesskey = "LTAI5t7UAZNeHDw7snnsTWex";
    //String secretkey = "Euv71yspESljbqnXfl0A13XlweN4rl";
    //String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String bucketName = "reggie-dish-images-boot";
    @Autowired
    AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    //上传的二进制文件
    public R<String> upload(MultipartFile file) throws IOException {
        //获取上传文件名
        String originalFilename = file.getOriginalFilename();
        //获取.的索引
        //例  aa.jdg获取 .jdg
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i);

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖+后缀
        String uuidName = UUID.randomUUID().toString() + suffix;

        //File f = new File(dir);
        //if (!f.exists()) {
        //    f.mkdirs();
        //}
        ////将上传的文件保存到服务端
        //File fi = new File(dir, uuidName);
        //
        ////将服务器的文件存到指定文件中
        //file.transferTo(fi);

        //创建Ossclient实例
        //三个参数
        //OSSClientBuilder oss = new OSSClientBuilder();
        //OSS build = oss.build(endpoint, accesskey, secretkey);
        //
        String objectName = "reggieImages/" + uuidName;
        //try {
        InputStream inputStream = file.getInputStream();

        aliOSSUtils.uploadFile(objectName,inputStream);

        //
        //    PutObjectRequest request = new PutObjectRequest(bucketName, objectName, inputStream);
        //    request.setProcess("true");
        //
        //    build.putObject(request);
        //} catch (OSSException oe) {
        //    System.out.println("Caught an OSSException, which means your request made it to OSS, "
        //            + "but was rejected with an error response for some reason.");
        //    System.out.println("Error Message:" + oe.getErrorMessage());
        //    System.out.println("Error Code:" + oe.getErrorCode());
        //    System.out.println("Request ID:" + oe.getRequestId());
        //    System.out.println("Host ID:" + oe.getHostId());
        //} catch (ClientException ce) {
        //    System.out.println("Caught an ClientException, which means the client encountered "
        //            + "a serious internal problem while trying to communicate with OSS, "
        //            + "such as not being able to access the network.");
        //    System.out.println("Error Message:" + ce.getMessage());
        //} finally {
        //    if (build != null) {
        //        build.shutdown();
        //    }
        //}

        return R.success(uuidName);
    }

    @GetMapping("/download")
    public void downlaod(String name, HttpServletResponse resp) throws IOException {
        //创建输入流通过输入流读取浏览器图片
        //FileInputStream fileInputStream = new FileInputStream(new File(dir+filename));
        //FileInputStream fis = new FileInputStream(new File(dir + name));
        //创建输出流将本地图片写到浏览器
        //ServletOutputStream os = resp.getOutputStream();
        //
        //resp.setContentType("image/jpeg");
        //
        //int len;
        //while ((len = fis.read()) != -1) {
        //    os.write(len);
        //}
        //fis.close();
        //os.close();

        //参数1:输入流 读取数据
        //参数2:输出流 写出数据

        OSS ossClient = new OSSClientBuilder().build(endpoint, accesskey, secretkey);
        String objectName = "reggieImages/" + name;

        try {
            //// 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            //OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            //// 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            //InputStream content = ossObject.getObjectContent();
            //if (content != null) {
            //    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            //    while (true) {
            //        String line = reader.readLine();
            //        if (line == null) break;
            //        System.out.println("\n" + line);
            //    }
            //    // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            //    content.close();
            //}
            OSSObject object = ossClient.getObject(bucketName, objectName);

            ServletOutputStream os = resp.getOutputStream();
            InputStream is = object.getObjectContent();

            IOUtils.copy(is, os);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

}

